package com.bittech.servlet.smallfileserver.web.config.listener;

import com.aliyun.oss.OSSClient;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * Author: secondriver
 * Created: 2018/10/21
 */
@WebListener
public class OssClientLoaderListener implements ServletContextListener {
    
    public static OSSClient ossClient;
    
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        String endpoint = servletContext.getInitParameter("oss_endpoint");
        if (endpoint == null || endpoint.isEmpty()) {
            throw new IllegalArgumentException("OSS endpoint must be not null/empty");
        }
        String accessKeyId = servletContext.getInitParameter("oss_accessKeyId");
        if (accessKeyId == null || accessKeyId.isEmpty()) {
            throw new IllegalArgumentException("OSS accessKeyId  must be not null/empty");
        }
        String accessKeySecret = servletContext.getInitParameter("oss_accessKeySecret");
        if (accessKeySecret == null || accessKeySecret.isEmpty()) {
            throw new IllegalArgumentException("OSS accessKeySecret must be not null/empty");
        }
        if (ossClient == null) {
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        }
    }
    
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        if (ossClient != null) {
            ossClient.shutdown();
            ossClient = null;
        }
    }
}
